import React from 'react'
import {connect} from 'react-redux';

import App from '../../common/App.jsx'
import Utils from '../../common/U.jsx'
import U from '../../common/U.jsx'
import HtmlEditor from '../common/HtmlEditor.jsx'
import OSSWrap from '../../common/OSSWrap';
import {
    Card,
    Form,
    Input,
    Upload,
    Tooltip,
    Icon,
    Radio,
    Progress,
    Button,
    message, InputNumber
} from 'antd';

import {Link} from 'react-router';
import BreadcrumbCustom from '../BreadcrumbCustom'
import CTYPE from "../../common/CTYPE";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const URL = {
    first: '工地',
    second: '工地列表',
    save: 'adm/court/save',
    detail: 'adm/court/court',
    go: 'app/court/courts',
    key: 'courtId',
};

class CourtEdit extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            progress: 0,
            namespace: '',
            id: parseInt(this.props.params.id),
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData = () => {
        let _this = this;
        let id = _this.state.id;
        if (id && id > 0) {
            App.api(URL.detail, {[URL.key]: id}).then(({title, city, address, location, img, video}) => {
                _this.props.form.setFieldsValue({title, city, address, location});
                this.setState({
                    image: img, video
                })
            })
        }
    };


    handleSubmit = (e) => {
        let _this = this;
        e.preventDefault();
        _this.props.form.validateFields((err, {title, city, address, location}) => {
            if (err) {
                Object.keys(err).forEach(key => {
                    message.warning(err[key].errors[0].message);
                });
            }

            App.api(URL.save, {
                title, city, address, location, img: this.state.image, video: this.state.video,
            }).then(() => {
                message.success('添加成功');
                URL.go && App.go(URL.go);
            })

        });
    };

    handleNewImage = (e, vr) => {
        if (!vr) {
            if (!e.target.files[0] || e.target.files[0].type.indexOf('image') < 0) {
                message.error('文件类型不正确,请选择图片类型');
                this.setState({
                    uploading: false,
                });
                return;
            }
            if (this.state.uploading) {
                message.loading('上传中');
                return;
            }
        }


        this.setState({uploading: true});

        OSSWrap.upload('', e.target.files[0], {
            progress: (p) => {
                this.setState({progress: Math.floor(p * 100)});
            }
        }).then((result) => {
            if (vr) {
                this.setState({
                    progress: 100,
                    video: result.url,
                    uploading: false,
                });
                return;
            }
            this.setState({
                progress: 100,
                image: result.url,
                uploading: false,
            });
        }).catch((err) => {
            message.error(err);
        });
    };


    render() {
        let _this = this;
        let id = this.props.params.id;
        const {getFieldDecorator} = _this.props.form;
        let content = this.state.content;
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'}/>
                <div className="ant-upload-text">上传</div>
            </div>
        );
        let progress = _this.state.progress;
        const imageUrl = this.state.imageUrl;
        return (
            <div className="common-edit-page">

                <BreadcrumbCustom first={URL.first} second={URL.second}/>

                <Form onSubmit={this.handleSubmit}>
                    <Card title="编辑图文" bordered={false}
                          extra={<Button type="primary" htmlType="submit">{id > 0 ? '保存' : '发布'}</Button>}
                          style={{minWidth: CTYPE.eidtMinWidth, maxWidth: CTYPE.eidtMaxWidth}}>
                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>标题</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('title', {})(
                                <Input placeholder={`建议输入字数不超过${CTYPE.maxlength.title}个字`}/>
                            )}
                        </FormItem>


                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>城市</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('city')(
                                <RadioGroup>
                                    {
                                        CTYPE.areaCode.map((item) => (
                                            <Radio value={item.value} key={item.value}>{item.label}</Radio>
                                        ))
                                    }
                                </RadioGroup>
                            )}
                        </FormItem>
                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>封面图</span>
                            )}
                            hasFeedback>
                            <p className="uploader">
                                <input className="file"
                                       type='file' onChange={this.handleNewImage}/>
                            </p>
                            {this.state.image && <img src={this.state.image} alt="" style={{width: 100}}/>}
                        </FormItem>


                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>VR视频</span>
                            )}
                            hasFeedback>
                            <p className="uploader">
                                <input className="file"
                                       type='file' onChange={(e) => this.handleNewImage(e, 'vr')}/>
                            </p>
                            {(progress == 100 || progress == 0) &&
                            <Progress percent={progress} showInfo={true} strokeWidth={5}/>}
                            {this.state.video && <video src={this.state.video} style={{width: 200}}/>}
                        </FormItem>

                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>地址</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('address', {})(
                                <Input placeholder={`详细地址`}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>经纬度</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('location')(
                                <Input placeholder={`经纬度`}/>
                            )}
                        </FormItem>

                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>定位参考</span>
                            )}
                            hasFeedback>

                            <a href="http://lbs.amap.com/console/show/picker"
                               target="_blank">点击获取经纬度</a>

                        </FormItem>


                    </Card>
                </Form>
            </div>
        )

    }
}

const CourseArticleEdit = Form.create()(CourtEdit);

export default CourseArticleEdit;
